/**
 * src/store/index.tsx
 * ------------------------------------
 * 全局状态管理
 * 1. AppContext：提供全局状态与 dispatch 方法
 * 2. appReducer：处理所有状态变更，包括用户、菜品、订单、购物车等
 * 3. AppProvider：包装应用根组件，提供 Context 上下文
 * 4. useAppContext：React Hook，用于组件中访问全局状态
 * 采用 React Context + useReducer 模式，避免引入额外状态管理库
 * 创建日期：2025-08-06
 */
import React, { createContext, useContext, useReducer, ReactNode } from 'react'
import { AppState, AppAction, Dish, Order, Category, User } from '../types'

/**
 * 应用初始状态
 * 定义应用启动时的默认状态
 */
const initialState: AppState = {
  currentUser: null,
  dishes: [],
  orders: [],
  cart: [],
  categories: [],
  feedbacks: [],
  ratings: [],
  loading: false,
  error: null
}

/**
 * 应用上下文
 * 提供全局状态和dispatch方法给所有子组件
 */
const AppContext = createContext<{
  state: AppState;
  dispatch: React.Dispatch<AppAction>;
}>({
  state: initialState,
  dispatch: () => null
})

/**
 * 应用状态管理器
 * 处理所有状态变更的纯函数，确保状态更新的可预测性
 * @param state 当前状态
 * @param action 要执行的动作
 * @returns 新的状态
 */
function appReducer(state: AppState, action: AppAction): AppState {
  switch (action.type) {
    // 用户相关操作
    case 'SET_USER':
      return { ...state, currentUser: action.payload }
    case 'LOGOUT':
      return { ...state, currentUser: null }
    
    // 菜品相关操作
    case 'SET_DISHES':
      return { ...state, dishes: action.payload }
    case 'ADD_DISH':
      return { ...state, dishes: [...state.dishes, action.payload] }
    case 'UPDATE_DISH':
      return {
        ...state,
        dishes: state.dishes.map(dish => 
          dish.id === action.payload.id ? action.payload : dish
        )
      }
    case 'DELETE_DISH':
      return {
        ...state,
        dishes: state.dishes.filter(dish => dish.id !== action.payload)
      }
    
    // 订单相关操作
    case 'SET_ORDERS':
      return { ...state, orders: action.payload }
    case 'ADD_ORDER':
      return { ...state, orders: [...state.orders, action.payload] }
    case 'UPDATE_ORDER':
      return {
        ...state,
        orders: state.orders.map(order => 
          order.id === action.payload.id ? action.payload : order
        )
      }
    
    // 购物车相关操作
    case 'SET_CART':
      return { ...state, cart: action.payload }
    case 'ADD_TO_CART': {
      const existingIndex = state.cart.findIndex(item => item.dishId === action.payload.dishId)
      
      if (existingIndex !== -1) {
        // 已存在，更新数量
        const updatedCart = [...state.cart]
        updatedCart[existingIndex] = {
          ...updatedCart[existingIndex],
          quantity: updatedCart[existingIndex].quantity + action.payload.quantity,
          totalPrice: (updatedCart[existingIndex].quantity + action.payload.quantity) * updatedCart[existingIndex].price
        }
        return { ...state, cart: updatedCart }
      } else {
        // 不存在，添加新项
        return { ...state, cart: [...state.cart, action.payload] }
      }
    }
    case 'REMOVE_FROM_CART':
      return {
        ...state,
        cart: state.cart.filter(item => item.dishId !== action.payload)
      }
    case 'UPDATE_CART_ITEM': {
      const { dishId, quantity } = action.payload
      
      if (quantity <= 0) {
        // 数量为0，移除项
        return {
          ...state,
          cart: state.cart.filter(item => item.dishId !== dishId)
        }
      } else {
        // 更新数量
        return {
          ...state,
          cart: state.cart.map(item => 
            item.dishId === dishId
              ? { ...item, quantity, totalPrice: quantity * item.price }
              : item
          )
        }
      }
    }
    case 'CLEAR_CART':
      return { ...state, cart: [] }
    case 'SET_CATEGORIES':
      return { ...state, categories: action.payload }
    case 'SET_FEEDBACKS':
      return { ...state, feedbacks: action.payload }
    case 'ADD_FEEDBACK':
      return { ...state, feedbacks: [...state.feedbacks, action.payload] }
    case 'UPDATE_FEEDBACK':
      return {
        ...state,
        feedbacks: state.feedbacks.map(feedback => 
          feedback.id === action.payload.id ? action.payload : feedback
        )
      }
    case 'SET_RATINGS':
      return { ...state, ratings: action.payload }
    case 'ADD_RATING':
      return { ...state, ratings: [...state.ratings, action.payload] }
    case 'UPDATE_RATING':
      return {
        ...state,
        ratings: state.ratings.map(rating => 
          rating.id === action.payload.id ? action.payload : rating
        )
      }
    case 'SET_LOADING':
      return { ...state, loading: action.payload }
    case 'SET_ERROR':
      return { ...state, error: action.payload }
    default:
      return state
  }
}

// Provider组件
export const AppProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(appReducer, initialState)
  
  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  )
}

// 自定义Hook
export const useAppContext = () => useContext(AppContext) 